import { defineStore } from 'pinia'
import { UserState } from '../types'
import store from '../pinia'
import UserService, { LoginData } from '@/service/system/user'
import Avatar from '@/assets/img_avatar.gif'
import { Response } from '@/api/http'
import { nextTick } from 'vue'
import { rsaEncrypt } from '@/utils'

const defaultAvatar = Avatar

const useUserStore = defineStore('user-info', {
  state: () => {
    return {
      account: '',
      areaId: 0,
      company: '',
      descName: '',
      description: '',
      mobile: '',
      real_name: '',
      avatar: defaultAvatar,
      rsaKey: '',
      token: '',
    }
  },
  actions: {
    // 登录操作
    doLogin(loginData: LoginData) {
      return new Promise<Response>((resolve, reject) => {
        // 首先根据用户名，获取加密字符串
        UserService.getRsaKey(loginData.username).then(res => {
          if (res.code == 200) {
            this.rsaKey = res.data
            // 获取了key之后，再请求登录
            loginData.password = rsaEncrypt(loginData.password, this.rsaKey)
            UserService.login(loginData).then(res => {
              if (res.code == 200) {
                if (res.data.type == 0) {
                  this.token = res.data.access_token
                }
              }
              resolve(res);
            })
          }
        })
      })
    },
    saveUser(userInfo: UserState) {
      return new Promise<UserState>((resolve) => {
        this.account = userInfo.account
        this.areaId = userInfo.areaId
        this.company = userInfo.company
        this.descName = userInfo.descName
        this.description = userInfo.description
        this.mobile = userInfo.mobile
        this.real_name = userInfo.real_name
        if (userInfo.avatar) {
          this.avatar = userInfo.avatar
        }
        resolve(userInfo)
      })
    },
    isTokenExpire() {
      return !this.token
    },
    logout() {
      return new Promise<void>(async (resolve) => {
        if (!this.isTokenExpire()) {
          // 调用接口退出登录
          await UserService.doLogout()
          this.$reset()
          localStorage.clear()
          sessionStorage.clear()
        }
        resolve()
      })
    },
  },
  presist: {
    enable: true,
    resetToState: true,
    option: {

    },
  },
})

export default useUserStore

/**
 * 返回一个Promise对象，目的是防止在非vue组件使用中的时候出现插件还没有出初始化完成导致持久化操作失败的bug。
 * 使用方式：
 *  import { useUserStoreContext } from '@/store/modules/user'
    useUserStoreContext().then((store) => {
      console.log(store.nickName)
    })
 * @returns Promise<typeof useUserStore>
 */
export async function useUserStoreContext() {
  await nextTick()
  return useUserStore(store)
}
